//
// Created by YueChuan on 2023/3/7.
//


#include "Login.h"
#include "ui_Login.h"
#include "clickedlabel.h"
#include "MainWindow.h"
#include <future>
#include "sqlModule.h"
Login::Login(QWidget *parent) :
        QWidget(parent), ui(new Ui::Login) {
    ui->setupUi(this);
    ui->listWidget->setVisible(false);
    this->setWindowIcon(QIcon(":/networkDisk.png"));
    connectDataBase();
    initCombo();

    connect(ui->label, SIGNAL(clicked()), this, SLOT(loginLabelSlot()));
    connect(ui->comboLable, SIGNAL(clicked()), this, SLOT(comboBoxShow()));
    connect(ui->listWidget, SIGNAL(currentItemChanged(QListWidgetItem * , QListWidgetItem * )), this,
            SLOT(on_currentItemChanged(QListWidgetItem * )));
    connect(ui->autoLogin, SIGNAL(stateChanged(int)), this, SLOT(on_autoLoginStateChanged(int)));

}

Login::~Login() {
    delete ui;
}

void Login::initCombo() {
    auto *file = new QFile("../Sources/res/password.txt");
    if (file->open(QIODevice::ReadOnly | QIODevice::Text)) {
        while (!file->atEnd()) {
            QList<QByteArray> list = file->readLine().replace('\r', "").replace('\n', "").split(',');
            QList<QByteArray> tempList;
            tempList.append(list[1]);
            tempList.append(list[2]);
            m_hash[QString(list[0])] = tempList;
        }
    } else {
        qDebug() << "open file error";
    }
    ui->listWidget->addItems(m_hash.keys());
    auto beginKey = m_hash.begin();
    ui->userNameLine->setText(beginKey.key());
    ui->passwordLine->setText(m_hash[beginKey.key()][0]);
    ui->autoLogin->setChecked(m_hash[beginKey.key()][1] == "1");

    file->close();
    file = nullptr;
    delete file;

}

void Login::connectDataBase() {
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setDatabaseName("networkDisk");
    db.setHostName("127.0.0.1");
    db.setUserName("root");
    db.setPassword("root");
    if (!db.open()) {
        qDebug() << db.lastError().text();
    }
}

void Login::upDateFile() {
    auto *file = new QFile("../Sources/res/password.txt");

    if (!file->open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::information(this, "保存", file->errorString());
    }
    bool remember = ui->remember->isChecked();
    QString uid = ui->userNameLine->text();
    QString password = ui->passwordLine->text();
    bool autoLogin = ui->autoLogin->isChecked();
    if (remember) {
        QList<QByteArray> lis;
        lis.push_back(password.toUtf8());
        if (autoLogin) {
            lis.push_back("1");
        } else {
            lis.push_back("0");
        }
        m_hash[uid] = lis;
    }
    QByteArray array = uid.toUtf8() + "," + m_hash[uid][0] + "," + m_hash[uid][1];

    for (auto &key: m_hash.keys()) {
        if (key == uid) {
            continue;
        }
        array += "\n" + key.toUtf8() + "," + m_hash[key][0] + "," + m_hash[key][1];
    }
    file->write(array, array.size());
    file->close();
}

void Login::autoLogin() {
    if (ui->autoLogin->isChecked()) {
        loginLabelSlot();
    }
}

void Login::loginLabelSlot() {
    QString uid = ui->userNameLine->text();
    QString passWord = ui->passwordLine->text();
//    std::this_thread::sleep_for(std::chrono::seconds(4));

    auto *query = new QSqlQuery();
    QString sql = "select password from password where uid = " + uid;
    query->prepare(sql);
    bool oko = query->exec();
    if (oko) {
        while (query->next()) {
            if (query->value(0).toString() == passWord) {
                QMessageBox::information(this, "登录", "登录成功");
                QString sqlStr = R"(update password set status="1" where uid=)" + uid;
                if(updateForm(query, sqlStr))
                    qDebug() <<"user status update succeed";
                upDateFile();
                auto *mainWindow = new MainWindow(uid);
                this->hide();
                mainWindow->show();
            } else {
                QMessageBox::information(this, "登录", "登录失败,密码错误");
                ui->passwordLine->clear();
                ui->passwordLine->setFocus();
            }
        }
    } else {
        qDebug() << "login select user error";
    }
    delete query;
}


void Login::comboBoxShow() {
    if (ui->listWidget->isVisible()) {
        ui->listWidget->setVisible(false);
        ui->comboLable->setPixmap(QPixmap(":/down.png"));
    } else {
        ui->listWidget->setVisible(true);
        ui->comboLable->setPixmap(QPixmap(":/up.png"));
    }

}

void Login::on_currentItemChanged(QListWidgetItem *current) {
    ui->userNameLine->setText(current->text());
    ui->listWidget->setVisible(false);
    ui->comboLable->setPixmap(QPixmap(":/down.png"));
    QList<QByteArray> list = m_hash[current->text()];
    QString passWord = list[0];
    bool autoLogin = list[1] == "1";
    if (passWord == "") {
        ui->passwordLine->clear();
        ui->autoLogin->setChecked(false);
        ui->remember->setChecked(false);
    } else {
        ui->remember->setChecked(true);
        ui->passwordLine->setText(passWord);
        ui->autoLogin->setChecked(autoLogin);
    }
}

void Login::on_autoLoginStateChanged(int state) {
    if (state == 2) {
        ui->remember->setChecked(true);
    }
}

void Login::keyPressEvent(QKeyEvent *event) {
    QWidget::keyPressEvent(event);
    if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
        loginLabelSlot();
    }
}

void Login::mousePressEvent(QMouseEvent *ev) {
    Q_UNUSED(ev);
    if (!ui->listWidget->isVisible()) {
        return;
    }
    ui->listWidget->setVisible(false);
    ui->comboLable->setPixmap(QPixmap(":/down.png"));
}



